<template>
  <el-dialog v-model="visible" title="选择客户进行护理设置" width="800px" :close-on-click-modal="false">
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="客户名:">
        <el-input v-model="searchForm.name" placeholder="请输入客户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border v-loading="loading" height="300px" style="width: 100%;"
      :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openProjectDialog(scope.row)">配置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-bar">
      <el-pagination v-model:current-page="pagination.cur" v-model:page-size="pagination.size" :total="pagination.total"
        :page-sizes="[5, 10, 20]" layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>

    <NursingLevelAndProject ref="projectDialogRef" @closeAndRefresh="handleCloseAndRefresh" />
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose } from 'vue'
import {inject} from 'vue'
const axios = inject("axios")

import { ElMessage } from 'element-plus'
import NursingLevelAndProject from '@/components/nursing/clientNursing/NursingLevelAndProject.vue'

const visible = ref(false)
const searchForm = ref({ name: '' })
const tableData = ref([])
const loading = ref(false)
const pagination = ref({ cur: 1, size: 5, total: 0 })
const projectDialogRef = ref()
const emit = defineEmits(['closeAndRefresh'])

const open = () => {
  visible.value = true

  // ✅ 强制重置状态
  searchForm.value.name = ''
  pagination.value.cur = 1
  pagination.value.size = 5
  pagination.value.total = 0
  tableData.value = []

  // ✅ 发起新请求
  query(1)
}

const query = async (page) => {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:9000/client/pageClientWithoutNursingLevel', {
      params: {
        cur: page,
        number: pagination.value.size,
        name: searchForm.value.name
      }
    })
    if (res.data.status === 200) {
      const list = res.data.data || []
      const total = res.data.total || 0

      // ✅ 修复关键逻辑：如果当前页数据为空且不是第一页，自动跳回第一页重新查询
      if (list.length === 0 && page > 1) {
        pagination.value.cur = 1
        return query(1)
      }

      tableData.value = list
      pagination.value.total = total

      // ✅ 空数据时提示（可选）
      if (list.length === 0 && total === 0) {
        ElMessage.info('当前暂无符合要求的客户')
      }
    } else {
      ElMessage.warning(res.data.msg || '查询失败')
      // ✅ 强制重置状态
      searchForm.value.name = ''
      pagination.value.cur = 1
      pagination.value.size = 5
      pagination.value.total = 0
      tableData.value = []
    }
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.cur = 1
  query(1)
}

const handleReset = () => {
  // ✅ 强制重置状态
  searchForm.value.name = ''
  pagination.value.cur = 1
  pagination.value.size = 5
  pagination.value.total = 0
  tableData.value = []
  query(1)
}

const handleCurrentChange = (page) => {
  pagination.value.cur = page
  query(page)
}

const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.cur = 1
  query(1)
}
const refreshList = () => {
  // 如果当前页只有一条数据并被移除，则回退到第一页
  if (tableData.value.length <= 1 && pagination.value.cur > 1) {
    pagination.value.cur = 1
  }
  query(pagination.value.cur)
}

const handleCloseAndRefresh = () => {
  refreshList() // 自己刷新
  emit('closeAndRefresh') // 告诉外层页面
}

const openProjectDialog = (client) => {
  ElMessage.success(`为客户「${client.name}」配置护理设置`)
  projectDialogRef.value.open(client.clientId)
}

defineExpose({ open })
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.pagination-bar {
  margin-top: 2%;
  margin-bottom: 2%;
  display: flex;
  justify-content: flex-end;
}
</style>
